﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using StudyLibrary.MyService;
using StudyLibrary.MenuForm;
using Common;

namespace StudyLibrary
{
    public partial class frmIndex : Form
    {
        Stack<string> backStack = new Stack<string>();
        Stack<string> forwardStack = new Stack<string>();


        public frmIndex()
        {
            InitializeComponent();
        }


        private void frmIndex_Activated(object sender, EventArgs e)
        {

            MyHotKey.RegisterHotKey(Handle, 100, MyHotKey.KeyModifiers.Alt, Keys.NumPad5);
            MyHotKey.RegisterHotKey(Handle, 101, MyHotKey.KeyModifiers.Ctrl, Keys.NumPad5);
        }

        private void frmIndex_Load(object sender, EventArgs e)
        {
            BindMenu();
            BindUrl();
            BindListFile(CommonService.Path_Root);
        }

        private void BindMenu()
        {
            tv_Menu.Nodes.Clear();

            TreeNode tree0 = new TreeNode();
            tree0.Text = "Index";
            tree0.Name = "Index";
            tree0.Tag = CommonService.Path_Root;
            tv_Menu.Nodes.Add(tree0);

            string _sqlSelect = "SELECT * FROM Menu ORDER BY ViewOrder ASC";
            System.Data.SQLite.SQLiteDataReader reader = SQLiteHelper.ExecuteReader(_sqlSelect);
            StringBuilder sb = new StringBuilder();
            while (reader.Read())
            {
                TreeNode tree = new TreeNode();
                tree.Text = reader.GetString(0);
                tree.Name = reader.GetString(0);
                tree.Tag = CommonService.Path_Root + reader.GetString(1);
                tv_Menu.Nodes.Add(tree);
            }
        }

        private void BindUrl()
        {
            tssBtn_Url.DropDownItems.Clear();

            ToolStripMenuItem tm0 = new ToolStripMenuItem();
            tm0.Text = "Manage";
            tm0.Name = "Manage";
            tm0.Tag = "manage";
            tm0.Click += ToolStripMenuItem_Click;
            tssBtn_Url.DropDownItems.Add(tm0);
            string _sqlSelect = "SELECT * FROM Url ORDER BY ViewOrder ASC";
            System.Data.SQLite.SQLiteDataReader reader = SQLiteHelper.ExecuteReader(_sqlSelect);
            StringBuilder sb = new StringBuilder();
            while (reader.Read())
            {
                ToolStripMenuItem tree = new ToolStripMenuItem();
                tree.Text = reader.GetString(0);
                tree.Name = reader.GetString(0);
                tree.Tag = reader.GetString(1);
                tree.Click += ToolStripMenuItem_Click;
                tssBtn_Url.DropDownItems.Add(tree);
            }

        }
        
        private void btn_Common_Click(object sender, EventArgs e)
        {
            string _path = "";
            string _btnName = ((Button)sender).Text;
            if (_btnName == "Architecture")
            {
               _path = CommonService.Path_Architecture;
            }
            else if (_btnName == "English")
            {
                _path = CommonService.Path_English;
            }
            else if (_btnName == "DataBase")
            {
                _path = CommonService.Path_DataBase;
            }
            else if (_btnName == "Computer")
            {
                _path = CommonService.Path_Computer;
            }
            else if (_btnName == "BaseKnowledge")
            {
                _path = CommonService.Path_BaseKnowledge;
            }
            else if (_btnName == "FrameWork")
            {
                _path = CommonService.Path_FrameWork;
            }
            else if (_btnName == "Live")
            {
                _path = CommonService.Path_Live;
            }
            else if (_btnName == "NetWork")
            {
                _path = CommonService.Path_NetWork;
            }
            else if (_btnName == "OtherLanguage")
            {
                _path = CommonService.Path_OtherLanguage;
            }
            else if (_btnName == "Toolkit")
            {
                _path = CommonService.Path_Toolkit;
            }
            else if (_btnName == "C#")
            {
                _path = CommonService.Path_CSharp;
            }
            else if (_btnName == "C++")
            {
                _path = CommonService.Path_Cpp;
            }
            else if (_btnName == "English")
            {
                _path = CommonService.Path_English;
            }
            else if (_btnName == "English")
            {
                _path = CommonService.Path_English;
            }
            //backStack.Clear();
            NewBrower(_path);
            BindListFile(_path);
            //System.Diagnostics.Process.Start("explorer.exe",_path);
        }


        private void list_File_DoubleClick(object sender, EventArgs e)
        {
            if (this.list_File.SelectedIndices.Count > 0)
            {
                Application.DoEvents();
                string _type = this.list_File.SelectedItems[0].SubItems[0].Text;
                string _path = this.list_File.SelectedItems[0].SubItems[2].Text;
                if (_type == "F")
                {
                    NewBrower(_path);
                    BindListFile(_path);
                }
                else
                {
                    string _ext = this.list_File.SelectedItems[0].SubItems[4].Text;
                    if (CommonService.ImageType.Contains(_ext))
                    {
                        System.Diagnostics.Process.Start(_path);
                    }
                    else if (CommonService.HtmlType.Contains(_ext))
                    {
                        System.Diagnostics.Process.Start("IExplore.exe", _path);
                    }
                    else if (CommonService.VideoType.Contains(_ext))
                    {
                        System.Diagnostics.Process.Start("dvdplay.exe", _path);
                    }
                    else
                    {
                        System.Diagnostics.Process.Start(_path);
                    }
                }
            }
        }

        private void BindListFile(string path)
        {

            //ImageList imgList = new ImageList();
            //imgList.ImageSize = new Size(1, 20);//分别是宽和高

            list_File.Items.Clear();

            DirectoryInfo TheFolder = new DirectoryInfo(path);
            foreach (DirectoryInfo folder in TheFolder.GetDirectories())
            {
                ListViewItem item = new ListViewItem();
                // item.SubItems.Add("F");
                item.SubItems[0].Text = "F";
                item.SubItems.Add(folder.Name);
                item.SubItems.Add(folder.FullName);
                item.SubItems.Add("");
                item.SubItems.Add("");
                list_File.Items.Add(item);
            }
            foreach (FileInfo file in TheFolder.GetFiles())
            {
                ListViewItem item = new ListViewItem();
                item.SubItems[0].Text = "";
                item.SubItems.Add(file.Name);
                item.SubItems.Add(file.FullName);
                list_File.Items.Add(item);
                item.SubItems.Add((file.Length/1024).ToString()+"KB");
                item.SubItems.Add(file.Extension);
            }
            //list_File.SmallImageList = imgList;
        }

        public void NewBrower(string path)
        {
            backStack.Push(path);//把当前输入的地址压栈
            forwardStack.Clear();//输入新地址要清理前进栈
        }

        public string BackBrower()
        {
            string path = "";
            if (backStack.Count > 1)//等于1的时候只有一个地址（当前地址），无法后退
            {
                forwardStack.Push(backStack.Pop());//弹出后退栈栈顶元素压入前进栈
                path = backStack.Peek();//返回后退栈栈顶元素，但不将其移除
            }

            return path;
        }

        public string ForwardBrower()
        {
            string path = "";
            if (forwardStack.Count > 0)//有元素就可以弹
            {
                path = forwardStack.Pop();
                backStack.Push(path);
            }
            return path;
        }

        private void tsBtn_Menu_Click(object sender, EventArgs e)
        {
            frmMenuManage f = new frmMenuManage();
            f.ShowDialog();
            if (f._isSuccess)
            {
                BindMenu();
            }
        }

        private void tsBtn_Back_Click(object sender, EventArgs e)
        {
           string path = BackBrower();
           if (!string.IsNullOrEmpty(path))
           {
               BindListFile(path);
           }
        }

        private void tsBtn_Forward_Click(object sender, EventArgs e)
        {
            string path = ForwardBrower();
            if (!string.IsNullOrEmpty(path))
            {
                BindListFile(path);
            }
        }

        private void tv_Menu_AfterSelect(object sender, TreeViewEventArgs e)
        {
 
        }

        private void tv_Menu_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            NewBrower(e.Node.Tag.ToString());
            BindListFile(e.Node.Tag.ToString());
        }

        private void tsBtn_OpenFolder_Click(object sender, EventArgs e)
        {
            if (list_File.SelectedItems.Count > 0)
            {
                string _isFolder = list_File.SelectedItems[0].SubItems[0].Text;
                if (_isFolder == "F")
                {
                    System.Diagnostics.Process.Start(list_File.SelectedItems[0].SubItems[2].Text);
                }
                else
                {
                    FileInfo fi = new FileInfo(list_File.SelectedItems[0].SubItems[2].Text);
                    string _path = list_File.SelectedItems[0].SubItems[2].Text;
                    string _dicPath = _path.Substring(0, _path.LastIndexOf("\\"));
                    if (Directory.Exists(_dicPath))
                    {
                        System.Diagnostics.Process.Start(_dicPath);
                    }
                }
            }
        }

        private void tsBtn_Import_Click(object sender, EventArgs e)
        {

            if (backStack.Count==0)
            {
                MessageBox.Show("destFolder is empty");
                return;
            }
            string _destPath = backStack.Peek();
            openFileDialog_Import.Title = "select aim folder";
            if (openFileDialog_Import.ShowDialog() == DialogResult.OK)
            {
                string[] _filePath = openFileDialog_Import.FileNames;
                if (_filePath!=null && _filePath.Length > 0)
                {
                    foreach (string s in _filePath)
                    {
                        if (File.Exists(s))
                        {
                            FileInfo fi = new FileInfo(s);
                            File.Move(s, _destPath + "\\" + fi.Name);
                            BindListFile(_destPath);
                        }
                        else
                        {
                            MessageBox.Show("not found!    ", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }

        private void tsBtn_Delete_Click(object sender, EventArgs e)
        {
            if (list_File.SelectedItems.Count > 0)
            {
                string _isFolder = list_File.SelectedItems[0].SubItems[0].Text;
                if (_isFolder != "F")
                {
                    if (MessageBox.Show("are you really delete this file?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string _path = list_File.SelectedItems[0].SubItems[2].Text;
                        if (File.Exists(_path))
                        {
                            //FileInfo fi = new FileInfo(_path);
                            File.Delete(_path);
                            BindListFile(backStack.Peek());
                        }
                        else
                        {
                            MessageBox.Show("not found!    ", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }

        private void tsBtn_ImportFolder_Click(object sender, EventArgs e)
        {

            if (backStack.Count == 0)
            {
                MessageBox.Show("destFolder is empty");
                return;
            }
            string _destPath = backStack.Peek();

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if ( fbd.ShowDialog() == DialogResult.OK)
            {
                string _sourcePath = fbd.SelectedPath;
                if (!string.IsNullOrEmpty(_sourcePath))
                {
                    if (Directory.Exists(_sourcePath))
                    {
                        DirectoryInfo di = new DirectoryInfo(_sourcePath);
                        Directory.Move(_sourcePath, _destPath + "\\" + di.Name);
                        BindListFile(backStack.Peek());
                    }
                    else
                    {
                        MessageBox.Show("not found!    ", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void moveToToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (list_File.SelectedItems.Count > 0)
            {
                string _isFolder = list_File.SelectedItems[0].SubItems[0].Text;
                string _sourcePath = list_File.SelectedItems[0].SubItems[2].Text;

                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.SelectedPath = CommonService.Path_Root;
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    string _destPath = fbd.SelectedPath;
                    if (_isFolder != "F")
                    {
                        if (File.Exists(_sourcePath))
                        {
                            FileInfo fi = new FileInfo(_sourcePath);
                            File.Move(_sourcePath, _destPath + "\\" + fi.Name);
                            BindListFile(backStack.Peek());
                        }
                        else
                        {
                            MessageBox.Show("not found!    ", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        if (Directory.Exists(_sourcePath))
                        {
                            DirectoryInfo fi = new DirectoryInfo(_sourcePath);
                            Directory.Move(_sourcePath, _destPath + "\\" + fi.Name);
                            BindListFile(backStack.Peek());
                        }
                        else
                        {
                            MessageBox.Show("not found!    ", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //this.notifyIcon1.Visible = false;
            //base.ShowInTaskbar = true;
            //this.Activate();
            //this.Show();
            //base.WindowState = FormWindowState.Normal;
        }

        private void frmIndex_SizeChanged(object sender, EventArgs e)
        {
            //if (this.WindowState == FormWindowState.Minimized)
            //{
            //    //this.notifyIcon1.Visible = true;
            //    this.ShowInTaskbar = false;
            //    this.Hide();
            //}
        }

        private void frmIndex_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (e.CloseReason == CloseReason.UserClosing)
            //{
            //    e.Cancel = true;
            //    this.WindowState = FormWindowState.Minimized;
            //    notifyIcon1.Visible = true;
            //    this.Hide();
            //    this.ShowInTaskbar = false;
            //    return;
            //}

        }

        private void frmIndex_Leave(object sender, EventArgs e)
        {

            MyHotKey.UnregisterHotKey(Handle, 100);
            MyHotKey.UnregisterHotKey(Handle, 101);
        }


        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100: //如果是我们注册的那个热键  
                            this.Show();
                            this.WindowState = FormWindowState.Normal;
                            break;

                        case 101:
                            this.WindowState = FormWindowState.Minimized;
                            this.Hide();
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            ToolStripMenuItem x = (ToolStripMenuItem)sender;
            string _path = x.Tag.ToString();
            if (_path == "manage")
            {
                frmUrl f = new frmUrl();
                f.ShowDialog();
                if (f._isSuccess)
                {
                    BindUrl();
                }
            }
            else
            {
                System.Diagnostics.Process.Start(_path);
            }
        }

        private void txtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Notepad.exe");
        }

        private void cmdToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("cmd.exe");
        }

        private void wordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("winword.exe");
        }

        private void fireWallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FireWallHelp.NetFwAddPorts("sql",1433,"TCP");
        }
    }
}
